/*
 * AddUserWithCcMenu.java
 *
 * Created on __DATE__, __TIME__
 */

package serverPresentation;

import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import server.ServerData;
import utils.Base64Processing;

import connection.CitizenCardInterface;
import connection.DatabaseConnection;
import connection.exception.CardErrorException;

public class AddUserWithCcMenu extends javax.swing.JFrame {

	private static final long serialVersionUID = 1L;

	/** Creates new form AddUserWithCcMenu 
	 * @throws CardErrorException */
	public AddUserWithCcMenu() throws CardErrorException {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}

		initComponents();

		Image im = Toolkit.getDefaultToolkit().getImage(
		"images/security-icon.gif");
		this.setIconImage(im);

		fillFields();
	}

	private void fillFields() throws CardErrorException {

		ImageIcon imageIcon = new ImageIcon("images/security-icon.gif");
		_pictureLabel.setIcon(imageIcon);
		
		String[] subjectNameArray = CitizenCardInterface.getFirstLastName();
		
		_firstNameBox.setText(subjectNameArray[0]);
		_lastNameBox.setText(subjectNameArray[1]);
		_addressBox.setText(CitizenCardInterface.getUserCity());
	}

	//GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		_pictureLabel = new javax.swing.JLabel();
		jLabel1 = new javax.swing.JLabel();
		_firstNameBox = new javax.swing.JTextField();
		jLabel2 = new javax.swing.JLabel();
		_lastNameBox = new javax.swing.JTextField();
		jLabel3 = new javax.swing.JLabel();
		_addressBox = new javax.swing.JTextField();
		_cancelButton = new javax.swing.JButton();
		_nextButton = new javax.swing.JButton();
		_includeUserPass = new javax.swing.JCheckBox();
		jLabel4 = new javax.swing.JLabel();
		jLabel5 = new javax.swing.JLabel();
		jLabel6 = new javax.swing.JLabel();
		_usernameBox = new javax.swing.JTextField();
		_passwordBox = new javax.swing.JPasswordField();
		_passwordConfBox = new javax.swing.JPasswordField();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("Adicionar Utilizador Usando Cart\u00e3o do Cidad\u00e3o");

		jLabel1.setText("Primeiro Nome");

		_firstNameBox.setEditable(false);

		jLabel2.setText("\u00daltimo Nome");

		_lastNameBox.setEditable(false);

		jLabel3.setText("Morada");

		_addressBox.setEditable(false);

		_cancelButton.setText("Cancelar");
		_cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				cancelButtonMouseClicked(evt);
			}
		});

		_nextButton.setText("Continuar >");
		_nextButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				nextButtonMouseClicked(evt);
			}
		});

		_includeUserPass.setText("Incluir Username e Password?");

		jLabel4.setText("Nome de Utilizador");

		jLabel5.setText("Palavra-Passe");

		jLabel6.setText("Confirma\u00e7\u00e3o Palavra-Passe");

		_passwordBox.setText("jPasswordField1");

		_passwordConfBox.setText("jPasswordField2");

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup().addContainerGap()
						.addComponent(_includeUserPass)
						.addContainerGap(184, Short.MAX_VALUE))
						.addGroup(
								layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.TRAILING)
												.addGroup(
														javax.swing.GroupLayout.Alignment.LEADING,
														layout.createSequentialGroup()
														.addGroup(
																layout.createParallelGroup(
																		javax.swing.GroupLayout.Alignment.LEADING)
																		.addComponent(
																				jLabel1)
																				.addComponent(
																						jLabel2)
																						.addComponent(
																								jLabel3))
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																										68,
																										Short.MAX_VALUE)
																										.addGroup(
																												layout.createParallelGroup(
																														javax.swing.GroupLayout.Alignment.TRAILING,
																														false)
																														.addComponent(
																																_lastNameBox)
																																.addComponent(
																																		_firstNameBox)
																																		.addComponent(
																																				_addressBox,
																																				javax.swing.GroupLayout.PREFERRED_SIZE,
																																				188,
																																				javax.swing.GroupLayout.PREFERRED_SIZE)))
																																				.addGroup(
																																						javax.swing.GroupLayout.Alignment.LEADING,
																																						layout.createSequentialGroup()
																																						.addGroup(
																																								layout.createParallelGroup(
																																										javax.swing.GroupLayout.Alignment.LEADING)
																																										.addComponent(
																																												jLabel4)
																																												.addComponent(
																																														jLabel5)
																																														.addComponent(
																																																jLabel6))
																																																.addPreferredGap(
																																																		javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																																		.addGroup(
																																																				layout.createParallelGroup(
																																																						javax.swing.GroupLayout.Alignment.LEADING,
																																																						false)
																																																						.addComponent(
																																																								_passwordConfBox)
																																																								.addComponent(
																																																										_passwordBox)
																																																										.addGroup(
																																																												layout.createSequentialGroup()
																																																												.addComponent(
																																																														_nextButton)
																																																														.addPreferredGap(
																																																																javax.swing.LayoutStyle.ComponentPlacement.UNRELATED,
																																																																javax.swing.GroupLayout.DEFAULT_SIZE,
																																																																Short.MAX_VALUE)
																																																																.addComponent(
																																																																		_cancelButton))
																																																																		.addComponent(
																																																																				_usernameBox,
																																																																				javax.swing.GroupLayout.DEFAULT_SIZE,
																																																																				166,
																																																																				Short.MAX_VALUE))))
																																																																				.addGap(46, 46, 46))
																																																																				.addGroup(
																																																																						layout.createSequentialGroup()
																																																																						.addGap(112, 112, 112)
																																																																						.addComponent(_pictureLabel,
																																																																								javax.swing.GroupLayout.PREFERRED_SIZE,
																																																																								144,
																																																																								javax.swing.GroupLayout.PREFERRED_SIZE)
																																																																								.addContainerGap(117, Short.MAX_VALUE)));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
						.addGap(38, 38, 38)
						.addComponent(_pictureLabel,
								javax.swing.GroupLayout.PREFERRED_SIZE,
								165,
								javax.swing.GroupLayout.PREFERRED_SIZE)
								.addGap(46, 46, 46)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
														.addComponent(
																jLabel1)
																.addPreferredGap(
																		javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				jLabel2)
																				.addPreferredGap(
																						javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																						.addComponent(
																								jLabel3))
																								.addGroup(
																										layout.createSequentialGroup()
																										.addComponent(
																												_firstNameBox,
																												javax.swing.GroupLayout.PREFERRED_SIZE,
																												javax.swing.GroupLayout.DEFAULT_SIZE,
																												javax.swing.GroupLayout.PREFERRED_SIZE)
																												.addPreferredGap(
																														javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																														.addComponent(
																																_lastNameBox,
																																javax.swing.GroupLayout.PREFERRED_SIZE,
																																javax.swing.GroupLayout.DEFAULT_SIZE,
																																javax.swing.GroupLayout.PREFERRED_SIZE)
																																.addPreferredGap(
																																		javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																		.addComponent(
																																				_addressBox,
																																				javax.swing.GroupLayout.PREFERRED_SIZE,
																																				javax.swing.GroupLayout.DEFAULT_SIZE,
																																				javax.swing.GroupLayout.PREFERRED_SIZE)))
																																				.addGap(27, 27, 27)
																																				.addComponent(_includeUserPass)
																																				.addPreferredGap(
																																						javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																																						.addGroup(
																																								layout.createParallelGroup(
																																										javax.swing.GroupLayout.Alignment.BASELINE)
																																										.addComponent(jLabel4)
																																										.addComponent(
																																												_usernameBox,
																																												javax.swing.GroupLayout.PREFERRED_SIZE,
																																												javax.swing.GroupLayout.DEFAULT_SIZE,
																																												javax.swing.GroupLayout.PREFERRED_SIZE))
																																												.addPreferredGap(
																																														javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																														.addGroup(
																																																layout.createParallelGroup(
																																																		javax.swing.GroupLayout.Alignment.BASELINE)
																																																		.addComponent(jLabel5)
																																																		.addComponent(
																																																				_passwordBox,
																																																				javax.swing.GroupLayout.PREFERRED_SIZE,
																																																				javax.swing.GroupLayout.DEFAULT_SIZE,
																																																				javax.swing.GroupLayout.PREFERRED_SIZE))
																																																				.addPreferredGap(
																																																						javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																																						.addGroup(
																																																								layout.createParallelGroup(
																																																										javax.swing.GroupLayout.Alignment.BASELINE)
																																																										.addComponent(jLabel6)
																																																										.addComponent(
																																																												_passwordConfBox,
																																																												javax.swing.GroupLayout.PREFERRED_SIZE,
																																																												javax.swing.GroupLayout.DEFAULT_SIZE,
																																																												javax.swing.GroupLayout.PREFERRED_SIZE))
																																																												.addGap(26, 26, 26)
																																																												.addGroup(
																																																														layout.createParallelGroup(
																																																																javax.swing.GroupLayout.Alignment.BASELINE,
																																																																false)
																																																																.addComponent(_nextButton)
																																																																.addComponent(_cancelButton))
																																																																.addContainerGap()));

		pack();
	}// </editor-fold>
	//GEN-END:initComponents

	private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt) {
		this.setVisible(false);
		ServerData.getServerData().getMainMenu().setVisible(true);
		this.dispose();
		return;
	}

	private void nextButtonMouseClicked(java.awt.event.MouseEvent evt) {
		String username = null, password = null, passwordConf = null;
		
		String firstName = _firstNameBox.getText();
		String lastName = _lastNameBox.getText();
		String address = _addressBox.getText();
		
		String certificate = null;
		
		try {
			certificate = Base64Processing.encodeData(CitizenCardInterface.getCertificate());
		} catch (CardErrorException e) {
			JOptionPane.showMessageDialog(this, "O cartão não está inserido no leitor!!");
			return;
		}
		
		if(_includeUserPass.isSelected()){
			username = _usernameBox.getText();
			password = new String(_passwordBox.getPassword());
			passwordConf = new String(_passwordConfBox.getPassword());
			
			if(username.isEmpty()||password.isEmpty()||passwordConf.isEmpty()){
				JOptionPane.showMessageDialog(this, "Uma vez que selecionou incluir par de autenticação deve preencher todos os campos.");
				return;
			}
			
			if(password.compareTo(passwordConf)!=0){
				JOptionPane.showMessageDialog(this, "A password que foi introduzida não corresponde à confirmação!!");
				return;
			}
		}
		
		DatabaseConnection dbConn = ServerData.getServerData().getDatabaseConnection();
		
		int result = dbConn.addUser(firstName, lastName, username, password, address, certificate);
		
		if(result != 1){
			JOptionPane.showMessageDialog(this, "Não foi possível adicionar o utilizador. Provavelmente já existe outro com a mesma identificação");
			return;
		}else{
			JOptionPane.showMessageDialog(this, "Utilizador adicionado com sucesso!!");
			this.setVisible(false);
			ServerData.getServerData().getMainMenu().setVisible(true);
			this.dispose();
		}		
	}

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				//new AddUserWithCcMenu().setVisible(true);
			}
		});
	}

	//GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JTextField _addressBox;
	private javax.swing.JButton _cancelButton;
	private javax.swing.JTextField _firstNameBox;
	private javax.swing.JCheckBox _includeUserPass;
	private javax.swing.JTextField _lastNameBox;
	private javax.swing.JButton _nextButton;
	private javax.swing.JPasswordField _passwordBox;
	private javax.swing.JPasswordField _passwordConfBox;
	private javax.swing.JLabel _pictureLabel;
	private javax.swing.JTextField _usernameBox;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JLabel jLabel6;
	// End of variables declaration//GEN-END:variables

}